(function( $ ){

    var methods = {
		init : function(options) {
		  
		  var settings = $.extend( {
		      size:{width:400,height:300},
		      clazz:'popup',
		      buttons:[],
		      title:'Aviso',
		      msg:false,
		      beforeShow:undefined,
		      afterClose:undefined,
		      target:undefined,
		      action:undefined
		  }, options);
		  
		  popup = create_popup(settings,$(this));

		  if(settings.beforeShow !=undefined ){
			  popup.bind('open',settings.beforeShow);
		  }
		  
		  if(settings.afterClose !=undefined ){
			  popup.bind('close',settings.afterClose);
		  }
		  

		  return this;
	  },
	  	open: function() { show_popup($(this).modalpop('widget'));},
	    close: function(){ close_popup($(this).modalpop('widget'));},
	    widget:function(){ return $(this).parent().parent();},
	    clean:function(){ $('.error_container',$(this)).remove();$('input',$(this)).val(undefined);$('select',$(this)).val(undefined)},
    };
    
    $.fn.modalpop = function(method){
    	// Method calling logic
        if ( methods[method] ) {
          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
        } else {
          $.error( 'Method ' +  method + ' does not exist on busqueda' );
        }  
    };
  
  
})( jQuery );

function create_popup(settings,body){
	popup = $('<div>');
	var time = new Date();
	
	id = 'popup_'+time.getTime();
	popup.attr('id', id);
	$(popup).css('display','none');
	$(popup).addClass(settings.clazz);
	$(popup).css('position','fixed');
	var main_container = $('<div>');
	$(main_container).addClass('cualquiera');
	title = create_title(settings,id);
	$(main_container).css('opacity',0);
	$(main_container).append(title);

	$(body).addClass('body');
	$(main_container).append(body);
	$(body).show();
	if((settings.buttons.length != 0 ||  settings.action != undefined) && !settings.msg ){
		buttons = create_buttons(settings,id);
		$(main_container).append(buttons);
	}
	$(popup).append(main_container);
	
	var target_selector = settings.target == undefined ? 'body': settings.target; 
	$(target_selector).append($(popup));
	if(settings.msg){
		show_popup($(popup));
	}
	
	return popup;
}

function create_title(settings,id){
	var header = $('<div>');
	$(header).addClass('title')
	
	var title = $('<div>');
	var close = $('<div>');
	$(title).text(settings.title);
	close.click(function(){close_popup($('#'+id))});
	close.text('X');
	close.addClass('close');
	header.append(close);
	header.append(title);
	return $(header);
}

function create_buttons(settings,id){
	buttons_container = $('<div class="buttons-container">');
	buttons_list = $('<ul>');
	
	button_ok = create_button({label:'ok',funcion:settings.action});
	$(buttons_list).append($(button_ok));
	button_cancel = create_button({label:'cancel',funcion:function(){close_popup($('#'+id))}});
	for(var i=0;i<settings.buttons.length;i++){
		button = create_button(setting.buttons[i]);
		$(buttons_list).append($(button));
	}
	
	

	
	
	$(buttons_container).append($(buttons_list));
	return $(buttons_container);
}

function create_button(settings){
	button_container = $('<li >');
	button = $('<span class="button-class">')
	button.text(settings.label);
	button.click(settings.funcion);
	$(button_container).append($(button));
	return $(button_container);
}

function create_overlay(){
	// fondo transparente
    // creamos un div nuevo, con dos atributos
    var bgdiv = $('<div>').attr({
                            id: 'modal-pop-overlay'
                            });
    
    // agregamos nuevo div a la pagina
    $(bgdiv).css({
   	 'position':'fixed',
       'left':0,
       'top':0,
       'background-color':'#dfdfdf',
       'opacity':0.75,
       'filter':'alpha(opacity=75)'});
    
    $('body').append(bgdiv);
    
    // obtenemos ancho y alto de la ventana del explorer
    var wscr = $(window).width();
    var hscr = $(window).height();
    
    //establecemos las dimensiones del fondo
    $('#modal-pop-overlay').css("width", wscr);
    $('#modal-pop-overlay').css("height", hscr);	
}

function center_popup(element){
	   // dimensiones de la ventana del explorer 
	   var wscr = $(window).width();
	   var hscr = $(window).height();
	   
	   var wcnt = $(element).width();
	   var hcnt = $(element).height();
	   
	   // obtener posicion central
	   var mleft = ( wscr - wcnt ) / 2;
	   var mtop = ( hscr - hcnt ) / 2;
	   
	   // estableciendo ventana modal en el centro
	   $(element).css("left", mleft+'px');
	   $(element).css("top", mtop+'px');
	}

function close_popup(popup){
	$('#modal-pop-overlay').remove();
	var height = $(popup).height();
	$(popup).animate({height:0},{duration:500, 
		complete:function(){
			$(popup).hide();
			$(popup).height(height);
			$(popup).children('div:first').css('opacity',0);
			$(popup).trigger('close');
		}});
	
}

function show_popup(popup){
	create_overlay();
	$(popup).trigger('open');
	center_popup($(popup));
	var height_temp = $(popup).height();
	var width_temp = $(popup).width();
	$(popup).height(0);
	$(popup).width(0);
	$(popup).show();
	$(popup).animate({height:height_temp,width:width_temp},{duration:500, step:function(now, fx ){
		center_popup(fx.elem);
    }, complete:function(){
    		$(popup).children('div:first').animate({opacity:1},'fast');
    		$(popup).height('');
    		$(popup).width('');
    } });
}

